package com.jml.task;


import com.jml.task.entity.LockInfo;
import com.jml.task.lock.impl.ZkTemporaryOrderNodeLock;
import com.jml.task.lock.impl.ZookeeperTemplateLock;
import com.jml.task.mapper.UserMapper;
import com.jml.task.utils.TranslationUtils;
import com.jml.task.utils.TranslationUtils001;
import com.jml.task.utils.ZkClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class JmlTask {

    @Value("${server.port}")
    private String serverPort;
    @Autowired
    private ZookeeperTemplateLock zookeeperTemplateLock;
    @Autowired
    private ZkTemporaryOrderNodeLock zkTemporaryOrderNodeLock;
    /**
     * 存放当前jvm线程 获取到锁的信息key 锁的id  value 锁的信息
     */
    private static Map<String, LockInfo> lockInfoMap = new ConcurrentHashMap<>();
    private static final String STATE_START = "start";
    private static final String STATE_STOP = "stop";
    @Autowired
    private UserMapper userMapper;
    //##创建定时任务线程池
    private ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
    @Autowired
    private TranslationUtils translationUtils;

    @Autowired
    private TranslationUtils001 translationUtils001;


    public JmlTask() {
         //续命三次 60s  60*3 180s
        scheduledExecutorService.scheduleAtFixedRate(new DetectionAlgorithm(), 0, 5, TimeUnit.SECONDS);
    }

    /**
     * 检测续命线程
     */
    class DetectionAlgorithm implements Runnable {
        @Override
        public void run() {
            lockInfoMap.forEach((k, lockInfo) -> {
                if (STATE_START.equals(lockInfo.getState())) {
                    //1.主动关闭连接
                    lockInfo.getLock().unLock();
                    //2.回滚
                    lockInfo.getTranslationUtils().rollback(lockInfo.getTransactionStatus());
                    //3.阻塞线程停止
                    lockInfo.getLockThread().interrupt();
                    //4.避免重复检测
                    lockInfoMap.remove(k);
                }
            });
        }
    }


    /**
     * 每隔2s执行定时任务  60 60 60 180s
     * 
     */
    @Scheduled(cron = "0/2 * * * * *")
    public  void taskService001() {
        try {
            //拉取数据库数据 调用第三方短信接口发送短信
            //获取锁
            zookeeperTemplateLock.getLock();
            //开启事务   translationUtils是多例的
            TransactionStatus begin = translationUtils.begin();
            //记录当前线程获取锁的信息，生成锁的ID
            String lockId = UUID.randomUUID().toString();
            System.out.println("taskService001-lockId:"+ lockId);
            System.out.println("taskService001-getTransactionStatus:"+ begin);
            System.out.println("taskService001-getTranslationUtils:"+ translationUtils);
            lockInfoMap.put(lockId, new LockInfo(lockId, Thread.currentThread(), STATE_START, zookeeperTemplateLock
                    , translationUtils, begin));
            log.info("[{}]正在调用阿里云发送短信..执行业务逻辑", serverPort);
            //事务
            userMapper.insert("jml" + System.currentTimeMillis(), 20);
            Thread.sleep(5000000);
            System.out.println("taskService001：业务执行完毕");
            translationUtils.commit(begin);
            lockInfoMap.put(lockId, new LockInfo(lockId, Thread.currentThread(), STATE_STOP, zookeeperTemplateLock));
            //释放锁
            zookeeperTemplateLock.unLock();
        } catch (Exception e) {
            System.out.println("taskService001：业务异常回滚");
            //api
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //释放锁
            zookeeperTemplateLock.unLock();
        }
    }
/*    @Scheduled(cron = "0/2 * * * * *")
    public void taskService() {
        try {
            //拉取数据库数据 调用第三方短信接口发送短信
            //获取锁
            zkTemporaryOrderNodeLock.getLock();
            log.info("[{}]正在调用阿里云发送短信", serverPort);
            //释放锁
            zkTemporaryOrderNodeLock.unLock();
        } catch (Exception e) {
            //释放锁
            zkTemporaryOrderNodeLock.unLock();
        }
    }*/

}
